//
//  AddressbookViewController.m
//  myhuibao
//
//  Created by li jun on 13-3-8.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "AddressbookViewController.h"
#import "BoxCell.h"
#import "config.h"
@interface AddressbookViewController ()

@end

@implementation AddressbookViewController
@synthesize mainTable;
@synthesize delegate;
@synthesize selectedIds;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self getSearchResult];
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [mainTable release];
    [super dealloc];
}
- (void) getSearchResult{
    
    ABAddressBookRef addressBook =ABAddressBookCreate();
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople (addressBook);
//    CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(addressBook);
    tableDataArray = [[NSMutableArray alloc] init];
    NSArray *ss = [selectedIds componentsSeparatedByString:@","];

    for (id person in (NSArray *) allPeople)
    {
        CFStringRef name = ABRecordCopyCompositeName(person);

        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"(" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@")" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""];
            personPhone = [personPhone stringByReplacingOccurrencesOfString:@" " withString:@""];

            if([Config isMobileNumber:personPhone])
            {
//            NSLog(@"Person label: %@ phone:%@",personPhoneLabel, personPhone);
            NSMutableDictionary * address = [[NSMutableDictionary alloc] init];// [NSDictionary dictionaryWithObject:name  forKey:@"name"];
            [address setValue:(NSString*)name forKey:@"name"];
            [address setValue:personPhoneLabel forKey:@"label"];
            [address setValue:personPhone forKey:@"phone"];
            bool selected = [self isArray:ss contain:personPhone];
            if (selected)
                [address setValue:@"YES" forKey:@"checked"];
            else
                [address setValue:@"NO" forKey:@"checked"];
            [tableDataArray addObject:address];
            }
        }
    }
//    for (id group in (NSArray *) allGroups)
//    {
//        
//    }
//    CFRelease(allGroups);
    CFRelease(allPeople);
    CFRelease(addressBook);
//    NSLog(@"%@",tableDataArray);
    [mainTable reloadData];

}
- (bool)isArray:(NSArray *)a contain:(NSString*)s
{
    for(NSString *ss in a)
    {
        if ([s isEqualToString:ss]) {
            return true;
        }
    }
    return false;
}

#pragma 列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"BoxCellIdentifier";
    
    BoxCell *cell = (BoxCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //        if (cell == nil) {
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"BoxCell" owner:nil options:nil];
    cell = [array objectAtIndex:0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    //        }
    
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    
    cell.lbName.text = [NSString stringWithFormat:@"%@-%@",[item valueForKey:@"name"],[item valueForKey:@"phone"]];
    cell.lbMemo.hidden = YES;
//    cell.lbMemo.text = [item valueForKey:@"phone"];
    cell.checked = [[item valueForKey:@"checked"] boolValue];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    BOOL checked = [[item valueForKey:@"checked"] boolValue];
    BoxCell *cell = (BoxCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (checked) {
        [cell setChecked:false];
        [item setValue:@"NO" forKey:@"checked"];

    }else{
        [cell setChecked:true];
        [item setValue:@"YES" forKey:@"checked"];

    }
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    //其他cell的事件
    
}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)doSave:(id)sender {
    NSString *ids=@"";
    NSString *names=@"";
    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        BOOL checked = [[item valueForKey:@"checked"] boolValue];
        if(checked)
        {
            ids = [ids stringByAppendingFormat:@"%@,",[item valueForKey:@"phone"]];
            names = [names stringByAppendingFormat:@"%@,",[item valueForKey:@"name"]];
        }
    }
    if([ids isEqualToString:@""]==NO){
        NSLog(@"%@", names);

        [delegate passNames:names withIds:ids];
        [self.navigationController popViewControllerAnimated:YES];

    }
}
@end
